package com.um.jdy.platform.user.manager;


import cn.hutool.core.lang.RegexPool;
import cn.hutool.core.util.ReUtil;
import com.um.jdy.common.base.enums.YesOrNo;
import com.um.jdy.common.commons.service.MobileService;
import com.um.jdy.common.member.enums.CodeKey;
import com.um.jdy.common.platform.code.LoginCode;
import com.um.jdy.common.platform.code.PartnersCode;
import com.um.jdy.common.platform.entity.po.CompanyUser;
import com.um.jdy.common.platform.entity.po.CompanyUserLog;
import com.um.jdy.common.platform.service.CompanyUserLogService;
import com.um.jdy.common.platform.service.CompanyUserService;
import com.um.jdy.common.system.enums.LoginType;
import com.um.jdy.platform.user.entity.dto.MobileDTO;
import com.um.jdy.platform.user.entity.dto.ResetPasswordDTO;
import com.um.jdy.platform.user.service.SessionUserService;
import com.um.springboot.starter.exception.ServiceException;
import com.um.springboot.starter.orm.entity.Response;
import com.um.springboot.starter.orm.manager.BaseManager;
import com.um.springboot.starter.utils.DesEncrypter;
import com.um.springboot.starter.utils.RSAUtil;
import com.um.springboot.starter.utils.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;


/**
 * 管理类：手机
 *
 * @author cs
 * 日期 2023/5/23
 * 版权所有 广州优匠科技有限公司
 */
@Component
public class MobileManager extends BaseManager<CompanyUserService> {

    @Autowired
    protected CompanyUserService companyUserService;

    @Autowired
    protected CompanyUserLogService companyUserLogService;

    @Autowired
    protected SessionUserService sessionUserService;

    @Autowired
    protected MobileService mobileService;

    @Autowired
    protected UserManager userManager;

    /**
     * 发送短信验证码
     *
     * @param prefix
     * @param mobile
     */
    public void sendCode(CodeKey prefix, String mobile) {
        if(!ReUtil.isMatch(RegexPool.MOBILE, mobile)){
            throw new ServiceException(LoginCode.MobileIllegal);
        }

        if (CodeKey.Signup == prefix && null != companyUserService.getEntity("mobile", mobile)) {
            throw new ServiceException(LoginCode.MobileExist);
        }

        if (CodeKey.Signin == prefix && null == companyUserService.getEntity("mobile", mobile)) {
            throw new ServiceException(LoginCode.MobileNotExist);
        }

        if (CodeKey.FindPwd == prefix && null == companyUserService.getEntity("mobile", mobile)) {
            throw new ServiceException(LoginCode.MobileNotExist);
        }

        mobileService.sendCode(prefix, mobile,getComId());
    }

    /**
     * 登录
     *
     * @param mobileSigninDTO
     */
    public Response signin(MobileDTO mobileSigninDTO) {
        if(!ReUtil.isMatch(RegexPool.MOBILE, mobileSigninDTO.getMobile())){
            throw new ServiceException(LoginCode.MobileIllegal);
        }

        //检查验证码
        if(StringUtil.getTrim(mobileSigninDTO.getCode()).equals("")){
            throw new ServiceException(LoginCode.CodeRequired);
        }

        CompanyUser companyUser = companyUserService.getEntity("mobile", mobileSigninDTO.getMobile());
        if (null == companyUser) {
            throw new ServiceException(LoginCode.MobileNotExist);
        }

        if (YesOrNo.No.name().equals(companyUser.getIsEnable())) {
            throw new ServiceException(LoginCode.AccountDisabled);
        }

        if(!mobileService.checkCode(CodeKey.Signin, mobileSigninDTO.getMobile(),mobileSigninDTO.getCode())){
            throw new ServiceException(LoginCode.CodeError);
        }

        CompanyUserLog loginLog = new CompanyUserLog();
        loginLog.setPlatformCompanyUserId(companyUser.getPlatformCompanyUserId());
        loginLog.setLoginDate(new Date());
        loginLog.setAction(LoginType.SignIn.getKey());
        loginLog.setUserNo(companyUser.getMobile());
        loginLog.setUserName(companyUser.getName());
        companyUserLogService.add(loginLog);

        return userManager.signinSuccess(companyUser);
    }

    /**
     * 验证原手机号
     *
     * @param mobileDTO
     */
    public void verify(MobileDTO mobileDTO) {
        CompanyUser user = companyUserService.getEntity("mobile", mobileDTO.getMobile());
        if (null == user) {
            throw new ServiceException(LoginCode.MobileNotExist);
        }
        mobileService.checkCode(CodeKey.EditPwd, user.getMobile(), mobileDTO.getCode());
    }

    /**
     * 绑定新手机号
     *
     * @param mobileDTO
     */
    public boolean bind(MobileDTO mobileDTO) {
        if(!ReUtil.isMatch(RegexPool.MOBILE, mobileDTO.getMobile())){
            throw new ServiceException(LoginCode.MobileIllegal);
        }

        if (null != companyUserService.getEntity("mobile", mobileDTO.getMobile())) {
            throw new ServiceException(LoginCode.MobileExist);
        }

        CompanyUser companyUser = sessionUserService.getTokenUser();
        mobileService.checkCode(CodeKey.EditPwd, companyUser.getMobile(), mobileDTO.getCode());
        companyUser.setMobile(mobileDTO.getMobile());
        companyUser.setPlatformCompanyUserId(companyUser.getPlatformCompanyUserId());
        return companyUserService.save(companyUser);
    }

    /**
     * 重置密码
     *
     * @param resetPasswordDTO
     * @return
     */
    public boolean resetPassword(ResetPasswordDTO resetPasswordDTO) {
        CompanyUser companyUser = companyUserService.getEntity("mobile",resetPasswordDTO.getMobile());
        if (companyUser == null) {
            throw new ServiceException(PartnersCode.MobileNotExist);
        }

        if(!mobileService.checkCode(CodeKey.FindPwd,resetPasswordDTO.getMobile(),resetPasswordDTO.getCode())){
            throw new ServiceException(LoginCode.CodeError);
        }

        String pwd = RSAUtil.simpleDecrypt(resetPasswordDTO.getPassword());
        DesEncrypter des = new DesEncrypter(DesEncrypter.CD_KEY);
        companyUser.setPassword(des.encrypt(pwd));
        companyUserService.update(companyUser);
        return true;
    }
}
